/**
* Module: 
* Description: 权限控制器
* Author: xsq
* Date: 2023/04/27 16:08:42
* LastEditAuthor: xsq
* LastEditTime: 2023/04/27 16:08:42
*/

const { getRuleList: ruleListServices, adminUserRules, ruleAuthById } = require('../services/rule');
const ruleModel = require('../model/rule');
const { connect } = require("../model/index");

/**
 * 权限列表
 * @method: get
 * @param {*} ctx 
 * @param {*} next 
 */
const getRuleList = async (ctx, next) => {
  const query = ctx.request.query;
  const pageSize = Number(query.pageSize || 10);
  const pageNum = Number(query.pageNum || 1) - 1;

  let { list: ruleList, pageCount } = await ruleListServices(query);
  ctx.body = {
    data: {
      datas: ruleList,
      pageNum: pageNum + 1,
      pageSize: pageSize,
      pageCount: pageCount,
    },
    code: 200,
    msg: '查询成功',
  };
  await next();
}

/**
 * 菜单下的权限
 * @method: get
 * @param {*} ctx 
 * @param {*} next 
 */
const ruleAuthFindById = async (ctx, next) => {
  const query = ctx.request.query;

  let { menuList, authList } = await ruleAuthById(query);
  ctx.body = {
    data: {
      authList: authList,
      menuList: menuList
    },
    code: 200,
    msg: '查询成功',
  };
  await next();
};

/**
 * 修改权限
 * @method: post
 * @param {*} ctx
 * @param {*} next
 */
const updateRule = async (ctx, next) => {
  const query = ctx.request.body;
  const saveData = {
    id: query.id,
    title: query.title,
    url: query.url,
    name: query.name,
    // pid: query.pid,
  };
  const sqlArr = [];
  for(let key in saveData) {
    if (key != 'id') {
      sqlArr.push(`${key}='${saveData[key]}'`);
    }
  }
  
  const database = ruleModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        UPDATE ${database}
        SET ${sqlArr.join(',')}
        WHERE id = ? and status = 1
      `,
      [Number(query.id)]
    );
    await connection.commit();
  } catch(err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }
  
  ctx.body = {
    data: {},
    code: 200,
    msg: '操作成功',
  };
  await next();
};

/**
 * 添加菜单
 * @method: post
 * @param {*} ctx 
 * @param {*} next 
 */
const addRule = async (ctx, next) => {
  const query = ctx.request.body;
  const saveData = {
    title: query.title || '',
    url: query.url || '',
    name: query.name || '',
    pid: query.pid, // 上级id
    is_menu: query.is_menu, // 菜单类型
    status: 1
  };
  let fields = [];
  let values = [];
  for(let key in saveData) {
    if (key != 'id') {
      fields.push(key);
      values.push(`'${saveData[key]}'`);
    }
  }

  const database = ruleModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        INSERT INTO ${database}
        (${fields.join(',')})
        VALUES (${values.join(',')})
      `
    );
    await connection.commit();
  } catch(err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: null,
    code: 200,
    msg: '操作成功',
  };
  await next();
}

/**
 * 删除菜单权限
 * @method: get
 * @param {*} ctx 
 * @param {*} next 
 */
const deleteRuleById = async (ctx, next) => {
  const query = ctx.request.query;
  const id = query.id;

  const database = ruleModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        DELETE FROM ${database}
        where id = ?
      `,
      [id]
    );
    await connection.commit();
  } catch(err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: {},
    code: 200,
    msg: '操作成功',
  };
  await next();
};

module.exports = {
  getRuleList,
  ruleAuthFindById,
  addRule,
  updateRule,
  deleteRuleById
}